package com.songcha.module_bookshelf.ui.fragment.bookshelf

import com.songcha.library_base.mvvm.base.BaseRepository
import com.songcha.library_business.bean.book.BookNetBean
import com.songcha.library_business.enums.BookDownloadStatus
import com.songcha.library_business.mvvm.BusinessRepository
import com.songcha.library_business.proxy.database.BookDetailDaoManager
import com.songcha.library_business.proxy.database.BookDownloadDaoManager
import com.songcha.library_business.proxy.database.BookReadProgressDaoManager
import com.songcha.library_business.proxy.database.BookShelfDaoManager
import com.songcha.library_network.bean.BaseListDataBean
import com.songcha.module_bookshelf.api.BookShelfApiManager
import com.songcha.module_bookshelf.structs.BookShelfItem
import io.reactivex.Observable

class BookShelfRepository:BusinessRepository() {
    fun getBookShelfList():Observable<MutableList<BookShelfItem>>{
        return Observable.create{
            val bookShelfList= BookShelfDaoManager.getBookShelfList()
            val ids= mutableListOf<String>()
            for(item in bookShelfList){
                ids.add(item.bookId)
            }
            val detailList= BookDetailDaoManager.getBookdetailListByIdList(ids)
            val readProgressList= BookReadProgressDaoManager.getReadProgressListByIdList(ids)
            if(detailList.size==readProgressList.size){
                val tmp= mutableListOf<BookShelfItem>()
                for(i in 0 until detailList.size){
                    val detailItem=detailList[i]
                    val readProgressItem=readProgressList[i]
                    val item= BookShelfItem().apply {
                        bookId=detailItem.bookId
                        author=detailItem.author
                        bookName=detailItem.name
                        thumb=detailItem.thumb
                        textCount=detailItem.textCount
                        progress=((readProgressItem.currentChapter/(detailItem.chapterCount*1.0f))*100)
                        val hasDownload= BookDownloadDaoManager.hasBookDownloaded(detailItem.bookId)
                        if(hasDownload){
                            downloadStatus= BookDownloadStatus.DOWNLOADED
                        }else{
                            downloadStatus= BookDownloadStatus.NO_DOWNLOAD
                        }
                    }

                    tmp.add(item)
                }
                it.onNext(tmp)

            }else{
                it.onNext(mutableListOf())
            }

            it.onComplete()
        }
    }

    fun getTodayRecommendBook():Observable<BaseListDataBean<BookNetBean>>{
        return BookShelfApiManager.api.getTodayRecommendBook(1)
    }
}